/*
 * @Author: 我想吃余 483766615@qq.com
 * @Date: 2025-11-09 13:09:49
 * @LastEditors: 我想吃余 483766615@qq.com
 * @LastEditTime: 2025-11-10 08:31:10
 * @FilePath: /code/oscode/thread/mythread.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <string>
#include <cstdio>
#include <pthread.h>
#include <unistd.h>

using namespace std;

//线程局部存储
__thread int g_val = 100;

//转为16进制
string toHex(pthread_t t)
{
    char id[64];
    snprintf(id, sizeof(id), "0x%x", t);
    return id;
}

void *threadRun(void *arg)
{
    cout << "thread: " << toHex(pthread_self()) << " g_val: " << ++g_val << " &g_val: " << &g_val << endl;
    return (void*)0;
}

int main()
{
    pthread_t t[5];
    for(int i = 0; i < 5; i++)
    {
        pthread_create(t + i, nullptr, threadRun, nullptr);
        sleep(1);
    }

    for(int i = 0; i < 5; i++)
        pthread_join(t[i], nullptr);
    return 0;
}



// void* thread_routine(void *arg)
// {
//     char* msg = (char*)arg;
//     int cnt = 3;
//     while(cnt--)
//     {
//         cout << "I am new thread, my name:" << msg << endl;
//         sleep(1);
//     }
// }

// int main()
// {
//     pthread_t tid[5];
//     for(int i = 0; i < 5; ++i)
//     {
//         char* buffer = (char*)malloc(64);
// 		sprintf(buffer, "thread %d", i);//thread name:Thread-i
//         pthread_create(&tid[i], nullptr, thread_routine, (void*)buffer);
//     }
//     cout << "I am main thread, my pid:" << getpid() << endl;

//     for(int i = 0; i < 5; ++i)
//     {
//         pthread_join(tid[i], nullptr);
//         cout << "thread-" << i << " quit!" << endl;
//     }
//     return 0;
// }